// 工具函数
function formatFileSize(bytes) {
    if (bytes === undefined || bytes === null) return 'Unknown';
    const units = ['B', 'KB', 'MB', 'GB', 'TB'];
    let size = bytes;
    let unitIndex = 0;
    while (size >= 1024 && unitIndex < units.length - 1) {
        size /= 1024;
        unitIndex++;
    }
    return `${size.toFixed(2)} ${units[unitIndex]}`;
}

function formatTimeRemaining(seconds) {
    if (seconds < 60) return `${Math.round(seconds)}秒`;
    if (seconds < 3600) return `${Math.round(seconds / 60)}分钟`;
    return `${Math.round(seconds / 3600)}小时${Math.round((seconds % 3600) / 60)}分钟`;
}

function getFileTypeIcon(filename) {
    const extension = filename.split('.').pop().toLowerCase();
    const iconMap = {
        // 视频文件
        mp4: 'video-icon.png',
        avi: 'video-icon.png',
        mkv: 'video-icon.png',
        // 音频文件
        mp3: 'audio-icon.png',
        wav: 'audio-icon.png',
        flac: 'audio-icon.png',
        // 文档文件
        pdf: 'pdf-icon.png',
        doc: 'doc-icon.png',
        docx: 'doc-icon.png',
        // 压缩文件
        zip: 'archive-icon.png',
        rar: 'archive-icon.png',
        '7z': 'archive-icon.png',
        // 默认图标
        default: 'file-icon.png'
    };
    return `icons/${iconMap[extension] || iconMap.default}`;
}

// 显示错误消息
function showError(message) {
    const errorMessage = document.getElementById('errorMessage');
    errorMessage.textContent = message;
    errorMessage.style.display = 'block';
    setTimeout(() => {
        errorMessage.style.display = 'none';
    }, 5000);
}

// 更新下载进度
function updateProgress(progress) {
    const progressContainer = document.getElementById('progressContainer');
    const progressFill = document.getElementById('progressFill');
    const progressPercent = document.getElementById('progressPercent');
    const progressSpeed = document.getElementById('progressSpeed');
    const progressRemaining = document.getElementById('progressRemaining');

    progressContainer.style.display = 'block';
    progressFill.style.width = `${progress.percent}%`;
    progressPercent.textContent = `${progress.percent}%`;
    progressSpeed.textContent = `${formatFileSize(progress.speed)}/s`;
    progressRemaining.textContent = `剩余时间: ${formatTimeRemaining(progress.timeRemaining)}`;
}

// 加载配置
async function loadConfig() {
    return new Promise((resolve) => {
        chrome.storage.sync.get(['config'], (result) => {
            resolve(result.config || {
                defaultDownloader: 'chrome',
                showPopupOnDownload: true,
                rememberLastPath: true,
                lastSavePath: '',
                fileTypeFilters: []
            });
        });
    });
}

document.addEventListener('DOMContentLoaded', async () => {
    // 获取DOM元素
    const elements = {
        closeBtn: document.getElementById('closeBtn'),
        settingsBtn: document.getElementById('settingsBtn'),
        browseBtn: document.getElementById('browseBtn'),
        chromeBtn: document.getElementById('chromeBtn'),
        thunderBtn: document.getElementById('thunderBtn'),
        idmBtn: document.getElementById('idmBtn'),
        openBtn: document.getElementById('openBtn'),
        openFolderBtn: document.getElementById('openFolderBtn'),
        cancelBtn: document.getElementById('cancelBtn'),
        downloadUrl: document.getElementById('downloadUrl'),
        fileName: document.getElementById('fileName'),
        savePath: document.getElementById('savePath'),
        fileNameDisplay: document.getElementById('fileNameDisplay'),
        fileSizeDisplay: document.getElementById('fileSizeDisplay'),
        fileTypeIcon: document.getElementById('fileTypeIcon'),
        safetyWarning: document.getElementById('safetyWarning')
    };

    let currentDownloadId = null;
    const config = await loadConfig();

    // 从storage获取下载信息
    chrome.storage.session.get(['downloadInfo'], (result) => {
        const info = result.downloadInfo;
        if (info) {
            // 更新表单
            elements.downloadUrl.value = info.url;
            elements.fileName.value = info.filename;
            elements.savePath.value = config.rememberLastPath ? config.lastSavePath : '';

            // 更新显示
            elements.fileNameDisplay.textContent = info.filename;
            elements.fileSizeDisplay.textContent = `大小: ${formatFileSize(info.size)}`;
            elements.fileTypeIcon.src = getFileTypeIcon(info.filename);

            // 显示安全警告
            if (info.safety && !info.safety.safe) {
                elements.safetyWarning.textContent = info.safety.warning;
                elements.safetyWarning.style.display = 'block';
            }

            // 根据检测结果启用/禁用下载按钮
            elements.thunderBtn.disabled = !info.hasThunder;
            elements.idmBtn.disabled = !info.hasIDM;
        }
    });

    // 事件监听器
    elements.closeBtn.addEventListener('click', () => window.close());

    elements.settingsBtn.addEventListener('click', () => {
        chrome.runtime.openOptionsPage();
    });

    elements.browseBtn.addEventListener('click', () => {
        chrome.downloads.showDefaultFolder();
    });

    // Chrome下载
    elements.chromeBtn.addEventListener('click', async () => {
        try {
            const downloadId = await chrome.downloads.download({
                url: elements.downloadUrl.value,
                filename: elements.fileName.value,
                saveAs: !config.rememberLastPath
            });
            currentDownloadId = downloadId;
        } catch (error) {
            showError(`Chrome下载失败：${error.message}`);
        }
    });

    // 迅雷下载
    elements.thunderBtn.addEventListener('click', async () => {
        try {
            await chrome.runtime.sendNativeMessage('com.xunlei.download', {
                url: elements.downloadUrl.value,
                filename: elements.fileName.value,
                path: elements.savePath.value
            });
            window.close();
        } catch (error) {
            showError(`调用迅雷失败：${error.message}`);
        }
    });

    // IDM下载
    elements.idmBtn.addEventListener('click', async () => {
        try {
            await chrome.runtime.sendNativeMessage('com.idm.download', {
                url: elements.downloadUrl.value,
                filename: elements.fileName.value,
                path: elements.savePath.value
            });
            window.close();
        } catch (error) {
            showError(`调用IDM失败：${error.message}`);
        }
    });

    // 打开文件
    elements.openBtn.addEventListener('click', () => {
        if (currentDownloadId) {
            chrome.downloads.open(currentDownloadId);
        }
    });

    // 打开文件夹
    elements.openFolderBtn.addEventListener('click', () => {
        if (currentDownloadId) {
            chrome.downloads.show(currentDownloadId);
        }
    });

    // 取消下载
    elements.cancelBtn.addEventListener('click', () => {
        if (currentDownloadId) {
            chrome.downloads.cancel(currentDownloadId);
        }
        window.close();
    });

    // 监听下载进度
    chrome.downloads.onChanged.addListener((delta) => {
        if (delta.id !== currentDownloadId) return;

        if (delta.state) {
            switch (delta.state.current) {
                case 'in_progress':
                    if (delta.bytesReceived && delta.totalBytes) {
                        const percent = Math.round((delta.bytesReceived.current / delta.totalBytes.current) * 100);
                        const speed = delta.bytesReceived.current / (Date.now() - delta.startTime);
                        const timeRemaining = (delta.totalBytes.current - delta.bytesReceived.current) / speed;
                        
                        updateProgress({
                            percent,
                            speed,
                            timeRemaining
                        });
                    }
                    break;
                case 'complete':
                    if (config.rememberLastPath) {
                        chrome.storage.sync.set({
                            config: {
                                ...config,
                                lastSavePath: elements.savePath.value
                            }
                        });
                    }
                    window.close();
                    break;
                case 'interrupted':
                    showError('下载已中断');
                    break;
            }
        }
    });
});